import 'package:connectivity/connectivity.dart';
import 'package:dio/dio.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:http_parser/http_parser.dart';
import 'package:mime_type/mime_type.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:webview_flutter/webview_flutter.dart';
import 'package:device_info_plus/device_info_plus.dart';
import 'package:image_picker/image_picker.dart';
import 'dart:io';

class MyRichTextEditor extends StatefulWidget {
  final String url;

  // 构造函数用于传递网页URL
  const MyRichTextEditor({Key? key, required this.url}) : super(key: key);

  @override
  _MyRichTextEditorState createState() => _MyRichTextEditorState();
}

class _MyRichTextEditorState extends State<MyRichTextEditor> {
  late WebViewController _controller;
  final ImagePicker _picker = ImagePicker();
  bool _permissionGranted = false;

  @override
  void initState() {
    super.initState();

    _controller = WebViewController()
      ..setJavaScriptMode(JavaScriptMode.unrestricted)
      ..setBackgroundColor(const Color(0x00000000))
      ..setNavigationDelegate(
        NavigationDelegate(
          onProgress: (int progress) {
            // Update loading bar.
          },
          onPageStarted: (String url) {},
          onPageFinished: (String url) {},
          onWebResourceError: (WebResourceError error) {},
          onNavigationRequest: (NavigationRequest request) {
            if (request.url.startsWith('myapp://openGallery')) { //传递信号值
              _openGallery();
              return NavigationDecision.prevent; // 阻止网页跳转
            }
            return NavigationDecision.navigate; // 允许网页跳转
          },
        ),
      )
      ..loadRequest(Uri.parse(widget.url));



    // 组件初始化时请求权限
    requestPhotosPermission();
    print(widget.url);
  }

  // 异步方法用于请求相册权限
  Future<void> requestPhotosPermission() async {
    try {
      // 获取设备信息以判断是不是Android设备以及Android版本
      final androidInfo = await DeviceInfoPlugin().androidInfo;
      // 根据Android版本请求不同的权限
      var status = androidInfo.version.sdkInt <= 32
          ? await Permission.storage.request() // Android 11及以下使用存储权限
          : await Permission.photos.request(); // Android 12及以上使用相册权限

      // 权限请求结果处理
      if (status.isGranted) {
        setState(() {
          _permissionGranted = true;
        });
      } else if (status.isDenied) {
        // 用户拒绝权限请求，显示提示信息
        ScaffoldMessenger.of(context).showSnackBar(
          const SnackBar(content: Text('相册权限被用户拒绝，请授予权限以继续')),
        );
      } else if (status.isPermanentlyDenied) {
        // 用户永久拒绝权限请求，引导用户到设置页面开启权限
        openAppSettings();
      }
    } catch (e) {
      // 错误处理
      if (kDebugMode) {
        print("获取设备信息或请求权限时出错：$e");
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    // 根据权限状态显示不同的界面
    return Scaffold(
      appBar: AppBar(
        title: const Text('记事本'),
      ),
      // body: _permissionGranted
      //     ? WebView(
      //   initialUrl: widget.url,
      //   javascriptMode: JavascriptMode.unrestricted,
      //   onWebViewCreated: (WebViewController webViewController) {
      //     _controller = webViewController;
      //     _controller.clearCache(); // 清除缓存
      //   },
      //   navigationDelegate: (NavigationRequest request) {
      //     if (request.url.startsWith('myapp://openGallery')) { //传递信号值
      //       _openGallery();
      //       return NavigationDecision.prevent; // 阻止网页跳转
      //     }
      //     return NavigationDecision.navigate; // 允许网页跳转
      //   },
      // )
      //     : const Center(
      //   child: Text('需要相册权限来继续'),
      // ),


      body: _permissionGranted
          ? WebViewWidget(
        controller: _controller,
      )
          : const Center(
        child: Text('需要相册权限来继续'),
      ),
    );
  }

  void _openGallery() async {

    final response = await pickImage();
    if (response != null) {
      String imageUrl = response.toString();
      print(imageUrl);
      // _controller.evaluateJavascript("receiveFromFlutter('$imageUrl')");
      _controller.runJavaScript("receiveFromFlutter('$imageUrl')");
    }

  }

  Future<String?> pickImage() async {
    final XFile? image = await _picker.pickImage(source: ImageSource.gallery);
    if (image != null) {
      var connectivityResult = await (Connectivity().checkConnectivity());
      if (connectivityResult == ConnectivityResult.none) {
        // 没有网络连接
        print('No internet connection');
      } else {
        // 有网络连接，执行上传操作
        final response = await uploadImage(File(image.path));
        return response;
      }
    }
    return null;
  }

  Future<String?> uploadImage(File imageFile) async {
    try {
      final prefs = await SharedPreferences.getInstance();
      final String? token = prefs.getString('userToken');

      String? mimeType = mime(imageFile.path);
      String fileType = mimeType?.split('/')[1] ?? 'jpeg';
      FormData formData = FormData.fromMap({
        'file': await MultipartFile.fromFile(imageFile.path, contentType: MediaType('image', fileType)),
      });

      Dio dio = Dio();
      dio.options.headers['token'] = token; // 根据服务器要求设置token，如果需要的话
      var response = await dio.post(
        'http://api.aiyuye.shop/memo/memoImage',
        data: formData,
      );

      if (response.statusCode == 200) {
        print('图片上传成功');
        return response.data; // 根据服务器返回的具体内容调整
      } else {
        print('图片上传失败：${response.statusCode}');
      }
    } catch (e) {
      print("上传图片时发生错误：$e");
    }
    return null;
  }
}
